/**未遂事故的列表页面 */
<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.faultTitle" placeholder="faultTitle" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox>
    </div>

    <!-- Note that row-key is necessary to get a correct row order. -->
    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">

      <el-table-column width="180px" align="center" label="未遂事故单编号" prop="faultId" />

      <el-table-column min-width="300px" label="未遂事故题目">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.faultTitle }}</span></template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="发生地点">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.faultLocation }}</span></template>
      </el-table-column>
      <el-table-column width="100px" label="发生时间">

        <template slot-scope="scope">
          <!-- <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span> -->
          <span>{{ scope.row.faultTime }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="发现人" width="95">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.faultUserCode.userName }}</span></template>
      </el-table-column>
      <el-table-column class-name="status-col" label="所属Team" width="110">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.faultTeam.deptName }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="裁决状态" width="80" prop="faultSatus" />

      <el-table-column align="center" label="操作" width="230">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fechData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item label="未遂事故单编号" prop="faultId">
          <el-input v-model="temp.faultId" />
        </el-form-item>
        <el-form-item label="未遂事故单题目" prop="faultTitle">
          <el-input v-model="temp.faultTitle" />
        </el-form-item>
        <el-form-item label="未遂事故发生地点" prop="faultLocation">
          <el-input v-model="temp.faultLocation" />
        </el-form-item>
        <el-form-item label="未遂事故发生时间" prop="faultTime">
          <el-date-picker v-model="temp.faultTime" type="datetime" placeholder="Please pick a date" />
          <!-- <el-input v-model="temp.faultTime " /> -->
        </el-form-item>
        <el-form-item label="未遂事故发现人" prop="faultUserCode">
          <el-select v-model="temp.faultUserCode.userName" class="filter-item" placeholder="Please select">
            <el-option v-for="item in personlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="未遂事故所属Team" prop="faultTeam">
          <el-select v-model="temp.faultTeam.deptName" class="filter-item" placeholder="Please select">
            <el-option v-for="item in deptlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchFaultList, deleteFaultList, editFault, fetchAllCount, getPersonList, getDeptList, createFault } from '@/api/fault'
import Sortable from 'sortablejs'
// import { parseTime } from '@/utils'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// arr to obj, such as { CN : "China", US : "USA" }

export default {
  name: 'Fault',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }

  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      editList: null,
      faultUserCode: null,
      faultTeam: null,
      sortable: null,
      oldList: [],
      newList: [],
      // 参数条件
      listQuery: {
        page: 1,
        limit: 20,
        faultTitle: null

      },
      personlist: null,
      deptlist: null,
      temp: {
        faultId: undefined,
        faultTitle: '',
        faultLocation: '',
        faultTime: new Date(),
        faultSatus: 1,
        faultTeam: '',
        faultUserCode: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create',
        detail: 'Detail'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'faultTime', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.fechData()
  },
  methods: {
    fechData() {
      getPersonList().then(response => {
        this.personlist = response.listName
      })
      getDeptList().then(response => {
        this.deptlist = response.listName
      })
      fetchAllCount().then(response => {
        this.total = response.count
      })
      fetchFaultList(this.listQuery).then(response => {
        this.listLoading = true
        this.list = response.ehsfaultList
        this.showList = response.ehsfaultList
        console.log('888888888888888' + response.ehsfaultList)
        this.listLoading = false
        this.oldList = response.map(v => v.id)
        this.newList = response.map(v => v.id).slice()
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      alert(this.dialogStatus)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const userName = this.temp.faultUserCode.userName
          alert(userName)
          const deptName = this.temp.faultTeam.deptName
          alert(deptName)
          this.temp.author = 'vue-element-admin'
          const query = { faultTime: this.temp.faultTime, faultLocation: this.temp.faultLocation, faultTitle: this.temp.faultTitle, userName: userName, deptName: deptName }
          createFault(query).then(() => {
            this.list.unshift(this.temp.userName)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            location.reload()
          })
        }
      })
    },
    handleDownload() {

    },
    showReviewer() {

    },
    handleFilter() {
      this.listQuery.page = 1
      this.fechData()
    },
    resetTemp() {
      this.temp = {
        faultId: undefined,
        faultTitle: '',
        faultLocation: '',
        faultTime: new Date(),
        status: 1,
        faultTeam: '',
        faultUserCode: ''
      }
    },
    handleDelete(row) {
      console.log(row)
      alert(row.faultId)
      deleteFaultList(row.faultId).then(response => {

      })
      this.fechData()
    },
    handleEdit(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1) // copy obj

      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      alert(this.dialogStatus)
      if (this.dialogStatus === 'detail') {
        location.reload()
      } else if (this.dialogStatus === 'update') {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            const query1 = JSON.parse(JSON.stringify(tempData))
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            const query = { faultId: query1.faultId, faultTitle: query1.faultTitle, userName: query1.faultUserCode.userName, deptName: query1.faultTeam.deptName }
            editFault(query).then(response => {
              this.obj = response
              this.faultId = response.faultId
              this.faultTitle = response.faultTitle
              alert('修改成功')
            })
            // 刷新页面
            location.reload()
          }
        })
      }
    },
    handleDetail(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1) // copy obj

      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // this.$router.push({ name: 'faultdetail', query: { faultId: row.faultId }})
    },
    // 格式化时间

    // formatJson(filterVal, jsonData) {
    //   return jsonData.map(v => filterVal.map(j => {
    //     if (j === 'timestamp') {
    //       return parseTime(v[j])
    //     } else {
    //       return v[j]
    //     }
    //   }))
    // },
    setSort() {
      const el = this.list[0]

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
</style>
